//
//  CameraViewController.m
//  QuanNengSaoMiaoZhuShou
//
//  Created by lanou3g on 16/3/11.
//  Copyright © 2016年 于博文. All rights reserved.
//

#import "CameraViewController.h"
#import "NetworkCableView.h"
#import "OCRController.h"
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import <ImageIO/ImageIO.h>

@interface CameraViewController ()<UIGestureRecognizerDelegate>
@property (weak, nonatomic) IBOutlet UIView *headView;

@property (weak, nonatomic) IBOutlet UIView *backView;//背景视图
@property (weak, nonatomic) IBOutlet UIView *bottomView;//底部视图
@property (weak, nonatomic) IBOutlet UIView *takePhotoButton;//拍照按钮
@property (nonatomic,strong)UISlider * focusChange;//改变焦距的控件
@property(nonatomic,strong)NetworkCableView * networkCableV;//网格线
@property (weak, nonatomic) IBOutlet UIButton *flashControl;//闪光灯控制按钮
@property (weak, nonatomic) IBOutlet UIButton *networkCableControl;//网格线控制按钮
@property(nonatomic,strong)UILabel * singleLable;//单张拍摄标签
@property(nonatomic,strong)UILabel * moreLable;//多张拍摄
@property(nonatomic,strong)UIScrollView * scrollView;//滑动栏
@property(nonatomic,strong)UIView * singleView;//单张拍摄提示视图
@property(nonatomic,strong)UIView * moreView;//多张拍摄提示视图
@property(nonatomic,strong)UIImageView * smallImageV;//左下角小图片
@property(nonatomic,strong)UILabel * numberLable;//左下角图片上的标签
@property (weak, nonatomic) IBOutlet UIButton *backButton;//返回按钮
@property(nonatomic,strong)UISwipeGestureRecognizer * swip;//屏幕的轻扫手势


//照相机相关
//AVCaptureSession(会话管理器)对象来执行输入设备和输出设备之间的数据传递
@property(nonatomic,strong)AVCaptureSession * session;
@property(nonatomic,strong)AVCaptureDeviceInput * videoInput;//输入设备（摄像头）
@property(nonatomic,strong)AVCaptureStillImageOutput * stillImageOutput;//照片输出流
@property (nonatomic, strong) AVCaptureVideoPreviewLayer* previewLayer;//预览图层
@property(nonatomic,assign)CGFloat beginGestureScale;//记录开始的缩放比例
@property(nonatomic,assign)CGFloat effectiveScale;//最后的缩放比例
@property(nonatomic,assign)CGFloat maxScaleAndCropFactor;//焦距的最大比例
@property(nonatomic,strong)NSMutableArray *imageArr;//寸照片的数组
@property (nonatomic,strong)UINavigationController *naV;
@end

@implementation CameraViewController
{
    BOOL isUsingFrontFacingCamera;//是否使用前面的摄像头
    BOOL isContinueTakePhoto;//是否连续拍照
}

+ (AVCaptureConnection *)connectionWithMediaType:(NSString *)mediaType fromConnections:(NSArray *)connectionArray {
    for (AVCaptureConnection * connection in connectionArray)
        for (AVCaptureInputPort * port in connection.inputPorts)
            if ([port.mediaType isEqual:mediaType])
                return connection;
    return nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
       //关闭电池栏
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
    //初始化设备
    [self initDevice];
    //初始化图层
    [self initView];
    //设置手势
    [self setUpGesture];
    
    isUsingFrontFacingCamera = NO;//是否使用前面的摄像头
    //初始化缩放比例
    self.effectiveScale = self.beginGestureScale = 1.0f;
    //闪光灯按钮初始标题
    [self.flashControl setTitle:@"自动" forState:(UIControlStateNormal)];
    //初始化取消按钮
    [self.backButton setTitle:@"取消" forState:(UIControlStateNormal)];
    //多张拍摄功能初始为单张
    isContinueTakePhoto = NO;
}


//取消按钮事件
- (IBAction)backButton:(UIButton *)sender {
    //
    if ([self.backButton.titleLabel.text isEqualToString:@"取消"]) {
         [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    else if([self.backButton.titleLabel.text isEqualToString:@"完成"]){
        OCRController *OCRVC = [[OCRController alloc]init];
        [OCRVC setValue:self.imageArr forKey:@"arrayForImage"];
         [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
         self.navigationController.navigationBarHidden  = NO;
        [self presentViewController:OCRVC animated:YES completion:nil];
        //返回按钮恢复
        [self.backButton setTitle:@"取消" forState:(UIControlStateNormal)];
        //轻扫恢复
        self.swip.enabled = YES;
    }else{
        NSLog(@"取消按钮不能实现对应的功能");
    }
}
//开启执行输入设备和输出设备之间数据传递的对象
- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:YES];
    self.navigationController.navigationBarHidden = YES;
     [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade];
    if (self.session) {
        [self.session startRunning];//输入设备和输出设备之间数据传递
    }
}
//结束执行输入设备和输出设备之间数据传递的对象
- (void)viewDidDisappear:(BOOL)animated{
    
    [super viewDidDisappear:YES];
    
    if (self.session) {
        
        [self.session stopRunning];
    }
}
//跟随手机转动视图
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - 私有方法
//初始化设备
-(void)initDevice{
    self.session = [[AVCaptureSession alloc] init];
    NSError *error;
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];//相机设备对象
    //更改这个设置的时候必须先锁定设备，修改完后再解锁，否则崩溃？？？
    [device lockForConfiguration:nil];
    //设置闪光灯为自动（共有三种状态）
    [device setFlashMode:AVCaptureFlashModeAuto];
    [device unlockForConfiguration];//解锁
    //输入设备初始化
    self.videoInput = [[AVCaptureDeviceInput alloc] initWithDevice:device error:&error];
    if (error) {
        NSLog(@"%@",error);
    }
    //照片输出流对象初始化
    self.stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
    //输出设置。AVVideoCodecJPEG   输出jpeg格式图片
    NSDictionary * outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG,AVVideoCodecKey, nil];
    [self.stillImageOutput setOutputSettings:outputSettings];
    
    if ([self.session canAddInput:self.videoInput]) {
        [self.session addInput:self.videoInput];
    }
    if ([self.session canAddOutput:self.stillImageOutput]) {
        [self.session addOutput:self.stillImageOutput];
    }
}
//初始化图层
-(void)initView{
    //初始化预览图层
    self.previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.session];
//    [self.previewLayer setVideoGravity:AVLayerVideoGravityResizeAspect];
//    self.previewLayer.frame = CGRectMake(0,-20,self.backView.frame.size.width, self.backView.frame.size.height+140);
    [self.previewLayer setVideoGravity:AVLayerVideoGravityResizeAspect];
    self.previewLayer.frame = CGRectMake(0,0,kSCreamWidth, kSCreamHeight-self.bottomView.frame.size.height-self.headView.frame.size.height);
    NSLog(@"%f,%f",self.backView.frame.size.width,self.previewLayer.frame.size.width);
    self.backView.layer.masksToBounds = YES;
    [self.backView.layer addSublayer:self.previewLayer];
    //添加网格线
    self.networkCableV = [[NetworkCableView alloc] initWithFrame:CGRectMake(0, 0,kSCreamWidth, kSCreamHeight-CGRectGetMaxY(self.headView.frame) - self.bottomView.frame.size.height)];
    self.networkCableV.backgroundColor = [UIColor clearColor];
    [self.backView addSubview:self.networkCableV];
    
    //焦距调节控件添加事件
    self.focusChange =[[UISlider alloc]initWithFrame:CGRectMake(30, self.backView.frame.size.height-30, self.backView.frame.size.width-60, 30)];
    [self.backView addSubview:self.focusChange];

    [self.focusChange setHidden:YES];
    [self.focusChange addTarget:self action:@selector(changeFocusAction:) forControlEvents:(UIControlEventValueChanged)];
    
    //闪光灯控制按钮初始标题
    [self.flashControl setTitle:@"关闭" forState:(UIControlStateNormal)];
    //网格线控制按钮的初始标题
    [self.networkCableControl setTitle:@"网格:开" forState:(UIControlStateNormal)];
    self.networkCableV.hidden = YES;
#pragma mark - 添加单张和多张拍摄相关的视图
    //1.添加单张和多张拍摄的选择栏
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(kSCreamWidth/2 -100 , 5,200, 20)];
    [self.scrollView setContentSize:CGSizeMake(self.scrollView.frame.size.width*4/3, 20)];
    self.scrollView.contentOffset = CGPointMake(0, 0);
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.pagingEnabled = YES;
    self.scrollView.bounces = NO;
    
    //添加lable
    self.singleLable = [[UILabel alloc] initWithFrame:CGRectMake(self.scrollView.frame.size.width/3,0, self.scrollView.frame.size.width/3, 20)];
    self.singleLable.text = @"单张拍摄";
    self.singleLable.textColor = [UIColor grayColor];
    self.singleLable.font = [UIFont systemFontOfSize:10];
    self.singleLable.textAlignment = NSTextAlignmentCenter;
    [self.scrollView addSubview:self.singleLable];
    
    self.moreLable = [[UILabel alloc]initWithFrame:CGRectMake(self.scrollView.frame.size.width*2/3,0, self.scrollView.frame.size.width/3, 20)];
    self.moreLable.textAlignment = NSTextAlignmentCenter;
    self.moreLable.text = @"多张拍摄";
    self.moreLable.font = [UIFont systemFontOfSize:10];
    self.moreLable.textColor = [UIColor grayColor];
    [self.scrollView addSubview:self.moreLable];
    [self.bottomView addSubview:self.scrollView];
    //2.添加上方的选中栏
    UIView * selectView = [[UIView alloc] initWithFrame:CGRectMake((kSCreamWidth/2 - 90) + self.scrollView.frame.size.width/3,0,self.scrollView.frame.size.width/3 -20,3)];
    selectView.backgroundColor = [UIColor cyanColor];
    [self.bottomView addSubview:selectView];
    //3.添加屏幕手势
    self.swip = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipAction:)];
    self.swip.direction = UISwipeGestureRecognizerDirectionLeft;//初始方向
    [self.view addGestureRecognizer:self.swip];
    //4.添加提示多张和单张拍摄的view
    self.singleView = [[UIView alloc] initWithFrame:CGRectMake(self.backView.frame.size.width/2-100, self.backView.frame.size.height/2-100, 200, 200)];
    self.singleView.backgroundColor = [UIColor blackColor];
    self.singleView.alpha = 0.4;
    UILabel * singleText = [[UILabel alloc] initWithFrame:CGRectMake(self.singleView.frame.size.width/2 -90, self.singleView.frame.size.height/2 -90, 180, 180)];
    singleText.text = @"单张拍摄";
    singleText.textColor = [UIColor whiteColor];
    singleText.textAlignment = NSTextAlignmentCenter;
    singleText.font = [UIFont systemFontOfSize:28];
    
    [self.singleView addSubview:singleText];
    [self.backView addSubview:self.singleView];
    self.singleView.hidden = YES;
    
    self.moreView = [[UIView alloc] initWithFrame:CGRectMake( self.backView.frame.size.width/2-100, self.backView.frame.size.height/2-100, 200, 200)];
    self.moreView.backgroundColor = [UIColor blackColor];
    self.moreView.alpha = 0.4;
    UILabel * moreText = [[UILabel alloc] initWithFrame:CGRectMake(self.moreView.frame.size.width/2 -90, self.moreView.frame.size.height/2 -90, 180, 180)];
    moreText.text = @"多张拍摄";
    moreText.textColor = [UIColor whiteColor];
    moreText.textAlignment = NSTextAlignmentCenter;
    moreText.font = [UIFont systemFontOfSize:28];
    
    [self.moreView addSubview:moreText];
    [self.backView addSubview:self.moreView];
    self.moreView.hidden = YES;
#pragma mark - 添加左边的显示小图片的视图（UIImageView和小lable）
    
    self.smallImageV = [[UIImageView alloc] initWithFrame:CGRectMake(self.bottomView.frame.size.width/12, self.bottomView.frame.size.height/4, self.bottomView.frame.size.height*3/5, self.bottomView.frame.size.height*3/5)];
    self.smallImageV.backgroundColor = [UIColor redColor];
    [self.bottomView addSubview:self.smallImageV];
    self.numberLable = [[UILabel alloc] initWithFrame:CGRectMake(self.smallImageV.frame.size.width-7,-7, 14, 14)];
    self.numberLable.text = nil;
    self.numberLable.textColor = [UIColor whiteColor];
    self.numberLable.textAlignment = NSTextAlignmentCenter;
    self.numberLable.backgroundColor = [UIColor cyanColor];
    self.numberLable.layer.borderColor = [UIColor whiteColor].CGColor;
    self.numberLable.layer.borderWidth = 1;
    self.numberLable.layer.cornerRadius = 7;
    self.numberLable.layer.masksToBounds = YES;
    [self.smallImageV addSubview:self.numberLable];
    //先隐藏
    self.smallImageV.hidden = YES;
    self.numberLable.hidden = YES;
}


//轻扫手势事件
-(void)swipAction:(UISwipeGestureRecognizer *)sender{
    if (sender.direction == UISwipeGestureRecognizerDirectionLeft) {
        //向左滑多张拍摄提示框显示
        self.moreView.hidden = NO;
        [UIView animateWithDuration:0.5 animations:^{
            //向左滑文字的改变
            self.scrollView.contentOffset = CGPointMake(self.scrollView.frame.size.width/3, 0);//位置改变
            self.moreLable.textColor = [UIColor cyanColor];//颜色改变
            self.singleLable.textColor = [UIColor grayColor];
            //将滑动方向改为向右
            sender.direction = UISwipeGestureRecognizerDirectionRight;
            self.moreView.alpha = 0;//多张拍摄提示框渐变为透明
        }];
        //
        self.singleView.alpha =0.5;
        self.singleView.hidden = YES;
        
        isContinueTakePhoto = YES;//多张拍摄开启
    }
    else{
        self.singleView.hidden = NO;
        //向右滑文字的改变
        [UIView animateWithDuration:0.5 animations:^{
        self.scrollView.contentOffset = CGPointMake(0, 0);
        self.singleLable.textColor = [UIColor cyanColor];
        self.moreLable.textColor = [UIColor grayColor];
        sender.direction = UISwipeGestureRecognizerDirectionLeft;
        self.singleView.alpha = 0;
        }];
        //恢复多张拍摄提示框的初始属性
        self.moreView.alpha = 0.5;
        self.moreView.hidden = YES;
        //单张模式下取消按钮文字为取消
        [self.backButton setTitle:@"取消" forState:(UIControlStateNormal)];
        //单张模式下小图片视图隐藏
        self.smallImageV.hidden = YES;
        self.numberLable.hidden = YES;
        isContinueTakePhoto = NO;//多张拍摄关闭
        isContinueTakePhoto = NO;//多张拍摄关闭
        
    }
}

#pragma 创建捏合手势--用于调整焦距
- (void)setUpGesture{
    
    UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinchGesture:)];
    pinch.delegate = self;
    [self.backView addGestureRecognizer:pinch];
}
//手势代理方法
- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    //如果手势是捏合手势，则将最后的缩放比例给到开始的缩放比例
    if ( [gestureRecognizer isKindOfClass:[UIPinchGestureRecognizer class]] ) {
        self.beginGestureScale = self.effectiveScale;
    }
    return YES;
}

#pragma mark --关于焦距
//1.缩放手势 用于调整焦距
- (void)handlePinchGesture:(UIPinchGestureRecognizer *)recognizer{
    
    BOOL allTouchesAreOnThePreviewLayer = YES;
    NSUInteger numTouches = [recognizer numberOfTouches], i;//获取触点数
    //遍历触点
    for ( i = 0; i < numTouches; ++i ) {
        //当前位置
        CGPoint location = [recognizer locationOfTouch:i inView:self.backView];
        //改变位置
        CGPoint convertedLocation = [self.previewLayer convertPoint:location fromLayer:self.previewLayer.superlayer];
        //如果改变位置不在预览层
        if ( ! [self.previewLayer containsPoint:convertedLocation] ) {
            allTouchesAreOnThePreviewLayer = NO;
            break;
        }
    }
    //如果所有的触点在预览层
    if ( allTouchesAreOnThePreviewLayer ) {
        //不缩小只放大
        self.effectiveScale = self.beginGestureScale * recognizer.scale;
        if (self.effectiveScale < 1.0){
            self.effectiveScale = 1.0;
        }
        //设置最大放大倍数(3.5),系统的videoMaxScaleAndCropFactor为67.5
        self.maxScaleAndCropFactor = [[self.stillImageOutput connectionWithMediaType:AVMediaTypeVideo] videoMaxScaleAndCropFactor] - 63.5;
        
        NSLog(@"%f,图层宽度%f",self.maxScaleAndCropFactor, self.previewLayer.frame.size.width);
        //如果手指放大倍数大于系统最大倍数，则置为系统最大放大倍数
        if (self.effectiveScale > self.maxScaleAndCropFactor )
            self.effectiveScale = self.maxScaleAndCropFactor ;
        //显示事务
        [CATransaction begin];
        [CATransaction setAnimationDuration:.025];
        [self.previewLayer setAffineTransform:CGAffineTransformMakeScale(self.effectiveScale, self.effectiveScale)];
        //设置
        self.focusChange.value = (self.effectiveScale - 1)/(self.maxScaleAndCropFactor - 1);
        [CATransaction commit];
        [self.focusChange setHidden:NO];
    }
    
}
//调节slider改变焦距
-(void)changeFocusAction:(UISlider*)sender{
    //取到焦距改变值
    self.effectiveScale = (self.maxScaleAndCropFactor -1) *sender.value +1;
    NSLog(@"%f,%f",sender.value,self.maxScaleAndCropFactor);
    
    [self.previewLayer setAffineTransform:CGAffineTransformMakeScale(self.effectiveScale, self.effectiveScale)];
}

#pragma mark - 头视图的网格打开按钮和闪光灯控制按钮
//1.闪光灯控制
- (IBAction)flashControl:(UIButton *)sender {
    NSLog(@"flashButtonClick");
    
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    //修改前必须先锁定
    [device lockForConfiguration:nil];
    
    //必须判定是否有闪光灯，否则如果没有闪光灯会崩溃
    if ([device hasFlash]) {
        
        if (device.flashMode == AVCaptureFlashModeOff) {
            device.flashMode = AVCaptureFlashModeOn;
            [sender setTitle:@"打开" forState:(UIControlStateNormal)];
        } else if (device.flashMode == AVCaptureFlashModeOn) {
            device.flashMode = AVCaptureFlashModeAuto;
            [sender setTitle:@"自动" forState:(UIControlStateNormal)];
        } else if (device.flashMode == AVCaptureFlashModeAuto) {
            device.flashMode = AVCaptureFlashModeOff;
            [sender setTitle:@"关闭" forState:(UIControlStateNormal)];
        }
    } else {
        NSLog(@"设备不支持闪光灯");
    }
    //打开闪光灯
    [device unlockForConfiguration];
}
//2.网格线控制
- (IBAction)networkCable:(UIButton *)sender {
    if (self.networkCableV.hidden == YES) {
        [self.networkCableV setHidden:NO];
        [self.networkCableControl setTitle:@"网格:关" forState:(UIControlStateNormal)];
    }else{
        [self.networkCableV setHidden:YES];
        [self.networkCableControl setTitle:@"网格:关" forState:(UIControlStateNormal)];
    }
}
#pragma mark - 切换镜头、方向改变、调用相机
//切换镜头
- (IBAction)changeCamera:(UIButton *)sender {
    AVCaptureDevicePosition desiredPosition;//枚举定义一个照像机的位置
    if (isUsingFrontFacingCamera){
        desiredPosition = AVCaptureDevicePositionBack;//给后面的照像机
    }else{
        desiredPosition = AVCaptureDevicePositionFront;//给前面的照像机
    }
    //遍历手机设备中的图像设备
    for (AVCaptureDevice *d in [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo]) {
        if ([d position] == desiredPosition) {//如果过该照相机的位置为指定的位置
            //预览层的处理数据传递的对象开始配置
            [self.previewLayer.session beginConfiguration];//
            //初始化输入设备
            AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:d error:nil];
            //遍历预览层的处理数据传递的对象的输入设备
            for (AVCaptureInput *oldInput in self.previewLayer.session.inputs) {
                //删除老的输入设备
                [[self.previewLayer session] removeInput:oldInput];
            }
            //添加新的输入设备
            [self.previewLayer.session addInput:input];
            //预览层的处理数据传递的对象提交配置
            [self.previewLayer.session commitConfiguration];
            break;
        }
    }
    
    isUsingFrontFacingCamera = !isUsingFrontFacingCamera;
}
//视频方向跟随手机设备的方向改变
- (AVCaptureVideoOrientation)avOrientationForDeviceOrientation:(UIDeviceOrientation)deviceOrientation
{
    AVCaptureVideoOrientation result = (AVCaptureVideoOrientation)deviceOrientation;
    if ( deviceOrientation == UIDeviceOrientationLandscapeLeft )
        result = AVCaptureVideoOrientationLandscapeRight;
    else if ( deviceOrientation == UIDeviceOrientationLandscapeRight )
        result = AVCaptureVideoOrientationLandscapeLeft;
    return result;
}

//调用相机
- (IBAction)takePhoto:(UIButton *)sender {
    NSLog(@"takephotoClick...");
    //获取连接
    AVCaptureConnection *videoConnection = nil;
    for (AVCaptureConnection *connection in self.stillImageOutput.connections) {
        for (AVCaptureInputPort *port in [connection inputPorts]) {
            if ([[port mediaType] isEqual:AVMediaTypeVideo] ) {
                videoConnection = connection;
                break;
            }
        }
        if (videoConnection) { break; }
    }
    //获取设备方向
    UIDeviceOrientation curDeviceOrientation = [[UIDevice currentDevice] orientation];
    //视频方向跟随设备方向更改
    AVCaptureVideoOrientation avcaptureOrientation = [self avOrientationForDeviceOrientation:curDeviceOrientation];
    [videoConnection setVideoOrientation:avcaptureOrientation];//连接对象设置对象
    [videoConnection setVideoScaleAndCropFactor:self.effectiveScale];//设置比例
    __weak __typeof(&*self)weakSelf = self;
    //获取图片
    [self.stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:
     ^(CMSampleBufferRef imageSampleBuffer, NSError *error) {
         
         CFDictionaryRef exifAttachments =
         CMGetAttachment(imageSampleBuffer, kCGImagePropertyExifDictionary, NULL);
         
         if (exifAttachments) {
             // Do something with the attachments.
         }
         
         // Continue as appropriate.
         NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageSampleBuffer];
         UIImage *t_image = [UIImage imageWithData:imageData];
         [weakSelf.imageArr addObject:t_image];
         
         if (isContinueTakePhoto == YES) {//多张拍摄模式
             NSLog(@"多张模式");
             //显示小图标视图
             weakSelf.smallImageV.hidden = NO;
             weakSelf.numberLable.hidden = NO;
             //图片张数的下标改变
             weakSelf.numberLable.text = [NSString stringWithFormat:@"%@",[NSNumber numberWithInteger:weakSelf.imageArr.count]];
             if (weakSelf.imageArr.count) {
                 //取消按钮变"完成"
                 [weakSelf.backButton setTitle:@"完成" forState:(UIControlStateNormal)];
                 //左下角显示小图片
                 
                 //轻扫事件关闭
                 weakSelf.swip.enabled = NO;
                 //返回
                 return;
             }
        }else{//单张拍摄模式
            OCRController * OCRVC = [[OCRController alloc] init];
            
            
            [OCRVC setValue:weakSelf.imageArr forKey:@"arrayForImage"];
           
             [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
            self.navigationController.navigationBarHidden  = NO;
            [weakSelf.navigationController pushViewController:OCRVC animated:YES];

             }
     }];
}
/*
 多张拍摄模式下亲扫事件关闭
 调焦距可用
 相片可点击
 取消按钮变成“完成”
 网格适配
 */

#pragma mark - 懒加载
-(NSMutableArray *)imageArr{
    if (!_imageArr) {
        _imageArr = [[NSMutableArray alloc] init];
    }
    return _imageArr;
}
/*
 多张拍摄模式下亲扫事件关闭
 调焦距可用
 相片可点击
 */
/*
 改变图片的大小
 -(UIImage *) imageCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth
 　　{
 　　CGSize imageSize = sourceImage.size;
 　　CGFloat width = imageSize.width;
 　　CGFloat height = imageSize.height;
 　　CGFloat targetWidth = defineWidth;
 　　CGFloat targetHeight = (targetWidth / width) * height;
 　　UIGraphicsBeginImageContext(CGSizeMake(targetWidth, targetHeight));
 　　[sourceImage drawInRect:CGRectMake(0,0,targetWidth, targetHeight)];
 　　UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
 　　UIGraphicsEndImageContext();
 　　return newImage;
 　　}
 
 
 */

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
